/**
 * Created by zhourb on 2017/12/17.
 */
var $ = require('jquery');
require('libs/bootstrap3-typeahead');
var $alert = require('libs/alert');
var $form = require('js-path/formValide.js');
$(function(){
    pageInit();
    mainFormValidInit();

    $('#userName').typeahead({
        source:function (query, process){
            $.post("api/v1/p/mms/ticket/queryEntInfoAmbiguous",
                {
                    query : query
                },
                function (result) {
                    if(result.code==200){
                        var data = [];
                        if(result.data){
                            $.each(result.data,function (index,obj) {
                                data.push(JSON.stringify(obj));
                            });
                        }
                        process(data);
                    }else{
                        $alert(result.message);
                    }
                });
        },
        items: 9999,
        matcher: function (item) {
            return true;
        },
        highlighter: function (item) {
            var obj = JSON.parse(item);
            return obj.entName+"-"+obj.userName;
        },
        updater: function (item) {
            var obj = JSON.parse(item);
            $("#userId").val(obj.userId);
            return obj.userName;
        }
    });
});
function pageInit() {
    var id = $.getUrlParam('id');
    if (id){
        $firstTarget = $("#titleInfo").find("span");
        //元素赋值
        $firstTarget.eq(0).text('推广人修改');
        loadAndInit(id);
    }
}
function loadAndInit(id) {
    $.ajax({
        url:'api/v1/p/mms/promotion/load',
        type:'post',
        data:{
            id:id
        },
        dataType:"json",
        success:function (result) {
            if(result.code==200){
                var data = result.data;
                dataInit(data);
            }else{
                $alert(result.message);
            }
        }
    })
}
function dataInit(data) {
    $("#id").val(data.id);
    $("#name").val(data.name);
    $("#phone").val(data.phone);
    $("#mail").val(data.mail);
    $("#address").val(data.address);
    $("#remark").val(data.remark);
    $("#userId").val(data.userId);
    $("#userName").val(data.userName);
    $("#sts").val(data.sts);

}

function mainFormValidInit(){
    $form({selector:'#main_form'},{
        name:{required:true},phone:{required:true},sts:{required:true}
    },{name:{required:'姓名不能为空'},
        phone:{required:'联系电话不能为空'},sts:{required:'状态不能为空'}
    },function () {
        var json = $('#main_form').serializeObject();
        json.sts = $("#sts").val();
        return json;
    },function (result) {
        if(result.code == 200){
            window.location.href="promotion-manage";
        }else{
            $alert(result.message);
        }
    })
}